package com.itheima.reggie.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.AddressService;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public List<Address> findBy() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        return addressMapper.selectList(wrapper);
    }

    @Override
    public void save(Address address) {
        //补齐参数
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);
        addressMapper.insert(address);
    }

    @Override
    public void find(Long id) {
        //设置为0
        Address address = new Address();
        address.setIsDefault(0);
        LambdaQueryWrapper<Address> addressLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressLambdaQueryWrapper.eq(Address::getUserId,UserHolder.get().getId());
        addressMapper.update(address,addressLambdaQueryWrapper);
        //将当前id设置为默认地址
        address.setIsDefault(1);
        address.setId(id);
        addressMapper.updateById(address);
    }

    @Override
    public Address js() {
        //查询当前用户is_default=1的记录
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getIsDefault,1)
               .eq(Address::getUserId,UserHolder.get().getId());
        Address address = addressMapper.selectOne(wrapper);
        return address;
    }

    @Override
    public Address findById(Long id) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getId,id);
        Address address = addressMapper.selectOne(wrapper);
        return address;
    }

    @Override
    public void deleted(Long ids) {
        addressMapper.deleteById(ids);
    }

    @Override
    public void put(Address address) {
        addressMapper.updateById(address);
    }
}
